#ifndef __CONN_H__
#define __CONN_H__

#include "sys.h"

#include "queue.h"
#include "msg.h"
#include "conf.h"



#define MAX_CONN 1024
#define MAX_EVENT 1024
#define MAX_RECV_QUEUE_SIZE 1024
#define MAX_SEND_QUEUE_SIZE 10


typedef enum _conn_state{
   IDEL,
   SND_READY,     //in thread read queue
   SNDING,        // thread are reading
   RCV_READY,     //in thread send queue
   RCVING,        //thread are writing

	CONNECTED,   //socket connected
	CONNECTING,  //socket connecting
	CLOSED,  //socket closed
}conn_state_t;

typedef  enum _conn_type{
	ACTIVE,   //active connect
	ACCEPT,  // accept connect
	NONE,  // not clear
}conn_type_t;

typedef struct _conn{
    int id;
    int sockfd;
    int node_idx;  //
    struct sockaddr_in addr;
    pthread_mutex_t  lock;  //proctec this data structure, especially snd_state and rcv_state
    conn_state_t  snd_state;
    conn_state_t rcv_state;
    conn_state_t conn_state;
    conn_type_t  conn_type;
    int thread;  //current in thread
    
    queue_t q_send;   //send msg queue
    queue_t q_recv;   //recv msg queue
    queue_t q_ack;    //waiting for ack msg queue
//  queue_t q_resend; //resend queue

	
    msg_t* recving_msg;       //msg that are recving on this connection
    msg_t* sending_msg;		//msg that are sending on this connection

   struct list_head  reconn_link;
}conn_t;


typedef struct _conn_tab{
	conn_t*  ctab[MAX_CONN];
	int size;
	pthread_mutex_t lock;
}conn_tab_t;

extern int conn_tab_init(conn_tab_t*  conn_tab);
extern int get_conn_state(conn_t* conn);
extern int set_conn_state(conn_t* conn, int state);

extern conn_t*  create_conn(int node_idx, int sockfd, struct sockaddr_in addr);
extern int destroy_conn(conn_t* conn);

extern int conn_tab_add(conn_t* conn);
extern int conn_tab_del(conn_t* conn);
extern conn_t* conn_tab_find_from_fd(int fd);
extern conn_t* conn_tab_find_from_node(node_t* node);

extern int add_reconn(conn_t* conn);

#endif 
